package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/response"
	"server/internal/services"
	"strings"
)

// MenuApi 菜单管理
var MenuApi = new(menuApi)

type menuApi struct {
	model.MenuRule
}

// Router 路由
func (a menuApi) Router(r *gin.RouterGroup) {
	api := r.Group("/menu", middleware.LoginVerification, middleware.PermissionVerification)
	//验证权限
	api.GET("/list", a.list)
	api.GET("/edit", a.detail)
	api.POST("/add", a.add)
	api.POST("/edit", a.edit)
	api.POST("/del", a.del)
	api.GET("/get_router", a.getRouter)

	//不验证权限
	api2 := r.Group("/menu", middleware.LoginVerification)
	api2.GET("/get_select", a.getSelect)
	api2.GET("/get_async_routes", a.getAsyncRoutes)

}

// List 列表
func (a menuApi) list(c *gin.Context) {

	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")
	response.SuccessList(c, services.Menu.GetTreeList(0, rules, groupIds), 0)
}

// Detail 单条
func (a menuApi) detail(c *gin.Context) {
	id := c.Query("id")

	detail := services.Menu.GetById(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a menuApi) add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if _, err := services.Menu.Create(a.MenuRule); err == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Error(c, "添加失败", err.Error())

	}
}

// Edit 编辑
func (a menuApi) edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if _, err := services.Menu.Update(a.MenuRule); err == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Error(c, "编辑失败")
	}
}

// Del 删除
func (a menuApi) del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	if err := services.Menu.Delete(param.Ids); err != nil {
		response.Error(c, err.Error())
	} else {
		response.Success(c, "", "删除成功")

	}
}

// GetAsyncRoutes 获取权限下菜单
func (a menuApi) getAsyncRoutes(c *gin.Context) {
	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")

	response.Success(c, services.Menu.GetTreeList(0, rules, groupIds), "")
}

// GetSelect 远程下啦
func (a menuApi) getSelect(c *gin.Context) {
	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")

	response.Success(c, services.Menu.GetSelect(rules, groupIds), "")
}

// GetRouter 获取菜单
func (a menuApi) getRouter(c *gin.Context) {

	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")
	response.Success(c, services.Menu.GetRouter(0, rules, groupIds), "")
}
